<template>
  <!-- 搜索栏 -->
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索栏 -->

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText" />
    <!-- 搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    />
    <!-- 联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @search="onSearch"
      @update-histories="searchHistories = $event"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
import { mapState } from 'vuex'

export default {
  name: 'SearchIndex',
  components: { SearchSuggestion, SearchHistory, SearchResult },
  props: {},
  data() {
    return {
      searchText: '',
      isResultShow: false,
      suggestions: [],
      searchHistories: getItem('serach-histories') || [],
    }
  },
  computed: { ...mapState(['user']) },
  watch: {
    searchHistories(val) {
      // 同步到本地存储
      setItem('serach-histories', val)
    },
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(searchText) {
      // 设置输入框为你要搜索的文本
      this.searchText = searchText

      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      const index = this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }

      // 记录搜索历史记录
      this.searchHistories.unshift(searchText)

      // 渲染搜索结果
      this.isResultShow = true
    },
  },
}
</script>

<style scoped lang="less"></style>
